package com.jsy.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.jsy.common.constant.RabbitMQConstant;
import com.jsy.common.dto.Message;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@CanalEventListener
public class SpuDataEventListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 自定义监听
     * destination canal安装时实例名称
     * schema要监听的数据库
     * table 要监听的表
     * eventType事件类型
     * @param eventType 事件类型
     * @param rowData 修改的数据
     */
    @ListenPoint(destination = "example",schema = "changgou_goods",table = {"tb_spu"},eventType = {CanalEntry.EventType.UPDATE, CanalEntry.EventType.DELETE})
    public void onEvent4(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        switch (eventType){
            case UPDATE:
                //获取审核状态、是否删除、id
                String status = getColumnValue(rowData.getAfterColumnsList(),"status");
                String isDelete = getColumnValue(rowData.getAfterColumnsList(),"is_delete");
                String id = getColumnValue(rowData.getAfterColumnsList(), "id");

                if ("1".equals(isDelete)){
                    sendMQMsg(Message.TYPE_GOODS_DELETE,id);
                }else if ("1".equals(status)){
                    sendMQMsg(Message.TYPE_GOODS_AUDIT,id);
                }
                break;
            default:
                //删除
                id =getColumnValue(rowData.getAfterColumnsList(),"id");
                sendMQMsg(Message.TYPE_GOODS_DELETE,id);
        }

    }

    /**
     * 更新静态化页面
     * @param type 消息类型
     * @param content 消息内容
     */
    private void sendMQMsg(String type, String content) {
        Message message = new Message(type, content);
        rabbitTemplate.convertAndSend(RabbitMQConstant.SPU_TOPIC_EXCHANGE, RabbitMQConstant.SPU_TOPIC_QUEUE,message);
    }

    /**
     * 获取一行中指定列名对应的值
     * @param columnsList 一行数据
     * @param columnName 列名
     * @return 列值
     */
    private String getColumnValue(List<CanalEntry.Column> columnsList, String columnName) {
        if(columnsList!=null&&columnsList.size()>0){
            for (CanalEntry.Column column : columnsList) {
                if (columnName.equals(column.getName())){
                    return column.getValue();
                }
            }
        }
        return null;
    }


}
